<?php
/*
@author: wjf
@contact: Hurrican
@software: PhpStorm
@create: 2022/8/8 13:35
*/
declare(strict_types=1);
namespace app\store\service\agent;

use app\common\service\agent\Common;
use app\common\service\BaseService;
use app\store\model\agent\Promoter;
use app\store\model\agent\Rel;
use app\store\model\User as UserModel;
use think\Exception;
use think\facade\Db;
use app\store\model\agent\Channel as ChannelModel;
use think\helper\Str;


class Channel extends BaseService
{
    /**
     * 获取列表
     * @param array $where
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList($params):array
    {
        return ChannelModel::with(['user'])->where(['is_del' => 0])
            ->order(['sort' => 'DESC','id' => 'DESC'])
            ->paginate($params['limit'] ?? 15)
            ->each(function (&$item) use($params){
                $item['mobile'] = $item['user']['mobile'];
                $item['username'] = $item['user']['username'];
                $item['balance'] = $item['user']['balance']; //可提现余额
                $item['freeze_balance'] = $item['user']['freeze_balance']; //冻结资金
                $item['achievement'] = (new Common())->getAchievement($item['user_id'],$params['start_time'] ?? null,$params['end_time'] ?? null);
                unset($item['user']);
            })
            ->toArray();
    }




    /**
     * 保存记录
     * @param $data
     * @return bool|int
     */
    public function save(array $data):bool
    {
        if(!empty($data['password']) && !empty($data['confirm_password'])){
            if($data['password'] != $data['confirm_password']){
                throwError('两次密码输入不一致,请重新输入');
            }
        }
        Db::startTrans();
        try {
            if(empty($data['id'])){
                //新增
                if(empty($data['password']) || empty($data['confirm_password'])){
                    throw new Exception('密码不能为空字符串');
                }
                $user = (new UserModel())->where(['mobile' => $data['mobile'],'is_delete' => 0])->find();
                if(!$user){
                    $user = UserModel::create([
                        'mobile' => $data['mobile'],
                        'nick_name' => $data['name'],
                        'username' => $data['username'],
                        'password' => encryption_hash((string)$data['password']),
                    ]);
                    if(!$user->user_id){
                        throw new Exception('insert user error');
                    }
                }else{
                    $user->username = $data['username'];
                    $user->password = encryption_hash((string)$data['password']);
                    $user->save();
                }
                //校验是否为渠道用户，渠道用户和推广用户只能为一个角色
                $promoter_user = Promoter::where(['user_id' => $user->user_id,'is_del' => 0])->find();
                if($promoter_user){
                    throw new Exception('已经是二级代理用户(推广员)了');
                }
                $condition = [
                    'user_id' => $user->user_id,
                    'is_del' => 0,
                ];
                $channel = ChannelModel::where($condition)->find();
                if(!$channel){
                    ChannelModel::create([
                        'name' => $data['name'],
                        'divide' => $data['divide'],
                        'sort' => $data['sort'],
                        'user_id' => $user->user_id,
                        'divide_type' => $data['divide_type'] ?? 1
                    ]);
                }

                //同时添加自己为玩家，且自己为自己的代理用户--todo 代理用户不想要2个手机号进行操作 ，自己买东西要能分到钱
                $condition = [
                    'user_id' => $user->user_id,
                    'promoter_user_id' => $user->user_id,
                    'is_del' => 0,
                ];
                $rel = Rel::where($condition)->find();
                if(!$rel){
                    Rel::create([
                        'user_id' => $user->user_id,
                        'promoter_user_id' => $user->user_id,
                    ]);
                }

            }else{
                //保存
                $channel = (new ChannelModel())->find($data['id']);
                $channel->name = $data['name'];
                $channel->divide = $data['divide'];
                $channel->sort = $data['sort'];
                $channel->divide_type = $data['divide_type'] ?? 1;
                $channel->save();

                //更新用户名和密码
                $user = UserModel::where(['is_delete' => 0,'user_id' =>$channel->user_id ])->find();
                $user->username = $data['username'];
                if(!empty($data['password']) && !empty($data['confirm_password'])){
                    $user->password = encryption_hash((string)$data['password']);
                }

                //同时更新下面的推广员的利润分成方式
                Promoter::update([
                    'divide_type' => $data['divide_type'] ?? 1
                ],['channel_id' => $channel->id]);

                $user->save();
            }
            Db::commit();
            return true;
        }catch (\Exception $e){
            Db::rollBack();
            throwError($e->getMessage());
            return false;
        }

    }

    /**
     * @param $username
     * @param $id
     */
    public function getReviewUsernameCheck($username,$id): bool
    {
        if(!$id){
            //新增
            $condition = [
                ['is_delete','=',0],
                ['username' ,'=',$username],
            ];
        }else{
            //编辑
            $channel_user = ChannelModel::where(['is_del' => 0,'id' => $id])->find();
            if(!$channel_user){
                throwError('此渠道不存在或已被删除');
            }
            $condition = [
                ['is_delete','=',0],
                ['username' ,'=',$username],
                ['user_id','<>',$channel_user->user_id]
            ];
        }
        $user = UserModel::where($condition)->find();
        if(!$user){
           return true;
        }
        return false;
    }


    /**
     * 删除
     * @param  $categoryId
     * @return bool
     * @throws \Exception
     */
    public function remove($id):bool
    {
        $channel = ChannelModel::where('is_del','=',0)->find($id);
        if(!$channel){
            throwError('不存在该渠道或已被删除');
        }
        // 判断是否存在代理用户
        $count = $this->getTotal($id);
        if ($count > 0) {
            throwError('该渠道下存在' . $count . '个代理，不允许删除');
            return false;
        }
        Db::startTrans();
        try {
            ChannelModel::update(['is_del' => 1],['id' => $id]);
            //同时解除代理用户和玩家绑定关系
            $condition = [
                'user_id' => $channel->user_id,
                'promoter_user_id' => $channel->user_id,
                'is_del' => 0,
            ];
            $rel = Rel::where($condition)->find();
            if($rel){
                $rel->is_del = 1;
                $rel->save();
            }
            //同时将用户账户置为空，避免账户重复
            UserModel::update(['username' => ''],['user_id' => $channel->user_id]);

            Db::commit();
            return true;
        }catch (\Exception $e){
            Db::rollBack();
            return false;
        }
    }


    /**根据渠道ID计算代理用户数量
     * @param $channel_id
     */
    public static function getTotal($channel_id): int
    {
        return Promoter::where('channel_id','=',$channel_id)->where('is_del','=',0)->count();
    }

    /**冻结、解冻提现操作
     * @return bool
     */
    public function getFrozenWithDraw($params):bool
    {
        $channel = ChannelModel::where('is_del','=',0)->find($params['id']);
        if(!$channel){
            throwError('不存在该渠道或已被删除');
        }
        ChannelModel::update(['is_with_draw' => $params['is_with_draw']],['id' => $params['id']]);
        return true;
    }


}